package com.yupi.yupicturebackend.manager.websocket.ws;

import com.yupi.yupicturebackend.manager.websocket.PictureEditHandler;
import com.yupi.yupicturebackend.manager.websocket.model.PictureEditMessageTypeEnum;
import com.yupi.yupicturebackend.manager.websocket.model.PictureEditRequestMessage;
import com.yupi.yupicturebackend.manager.websocket.model.PictureEditResponseMessage;
import com.yupi.yupicturebackend.manager.websocket.ws.BaseMessageHandler;
import com.yupi.yupicturebackend.model.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Component("EXIT_EDIT")
public class ExitEditHandler extends BaseMessageHandler {
    @Override
    public void handle(PictureEditRequestMessage request,
                       WebSocketSession session,
                       User user,
                       Long pictureId,
                       PictureEditHandler context) throws Exception {
        Long editingUserId = context.getPictureEditingUsers().get(pictureId);
        if (editingUserId != null && editingUserId.equals(user.getId())) {
            context.getPictureEditingUsers().remove(pictureId);

            PictureEditResponseMessage response = new PictureEditResponseMessage();
            response.setType(PictureEditMessageTypeEnum.EXIT_EDIT.getValue());
            response.setMessage(String.format("%s退出编辑图片", user.getUserName()));
            response.setUser(userService.getUserVO(user));

            broadcastToPicture(pictureId, response, null, context);
        }
    }
}